<?php

namespace app\services;

use EasyWeChat\Factory;
use plugin\admin\app\model\User;

class QrcodeService
{
    public static function generate($id, $type = 'article')
    {
        $config = ConfigService::getByGroup('wechat');
        $app = Factory::miniProgram([
            'app_id' => $config['wechat_app_id'],
            'secret' => $config['wechat_app_secret'],
            'response_type' => 'array'
        ]);

        $url = '';

        switch ($type) {
            case 'article':
                $url = '/pages/public/notice/system';
                break;
            case 'goods':
                $url = '/pages/classify/goods/info';
                break;
        }

        $user = User::where('id', get_user_id())->first();

        $response = $app->app_code->get($url . '?invite_code=' . $user['invite_code'] . '&id=' . $id, [
            'env_version' => ConfigService::get('wechat_mini_program_code_version')
        ]);

        $sign = md5($id . get_user_id() . $type);

        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $response->saveAs(public_path() . '/mini_program_qrcode', $sign  . '.png');
            $inviteQrcodeUrl = full_url('/mini_program_qrcode/' . $sign . '.png');

            return $inviteQrcodeUrl;
        }

        throw new \Exception('生成二维码失败');
    }
}